package com.wmlt.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.wmlt.dao.UserDao;
import com.wmlt.dao.impl.UserDaoImpl;
import com.wmlt.entity.Article;
import com.wmlt.entity.LayuiResponseData;
import com.wmlt.entity.User;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import com.wmlt.entity.UserResponseData;
import com.wmlt.service.UserService;
import com.wmlt.service.impl.UserServiceImpl;
import com.wmlt.util.CookieUtils;
import com.wmlt.util.GetRequestJsonUtils;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

//用户api
public class UserApi extends HttpServlet {
    UserDao userDao = new UserDaoImpl();
    UserService userService = new UserServiceImpl();

    protected void adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        User user = new User();
        UserService userService = new UserServiceImpl();
        user = userService.adminLogin(request.getParameter("username"), request.getParameter("password"));
        JSONObject json = new JSONObject();
        String data = json.toJSONString(user);
        request.getSession().setAttribute("user", user);
        response.getWriter().println(data);

    }

    protected void getUserNumber(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("获取用户人数");
        response.setContentType("text/html;charset=utf-8");
        UserService userService = new UserServiceImpl();
        response.getWriter().println(userService.getUserNumber());

    }

    protected void getAllUserInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        UserService userService = new UserServiceImpl();
        List<User> userList = userService.getAllUserInfo(request.getParameter("username"), 0, 0);
        LayuiResponseData data = new LayuiResponseData();
        data.setCode(200);
        data.setMsg("成功");
        UserDao userDao = new UserDaoImpl();
        data.setCount(userDao.getUserNumber());
        data.setData(userList);
        System.out.println(userList.size());
        String dataStr = JSON.toJSONString(data);
        response.getWriter().println(dataStr);

    }

    //删除用户  参数1 用户id   参数2  令牌
    protected void deleteUserInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        UserService userService = new UserServiceImpl();
        String[] userIdArr = request.getParameterValues("userId[]");
        int[] userIdArrInt = Arrays.stream(userIdArr).mapToInt(Integer::parseInt).toArray();
        int result = userService.deleteUserInfo(userIdArrInt);
        System.out.println(result);
        LayuiResponseData data = new LayuiResponseData();
        data.setCode(result);
        data.setMsg(result != 0 ? "成功" : "失败");
        data.setData(null);
        response.getWriter().println(result);
    }

    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("register");

    }

    protected void sendMessage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        System.out.println("-----------------发送验证码开始-----------------");
        String mobile = request.getParameter("phone");
        System.out.println(mobile);
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://gbk.api.smschinese.cn");
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码
        Random random = new Random();
        String verificationCode = "";
        for (int i = 0; i < 6; i++) {
            verificationCode += (int) (Math.random() * 10);
        }
        ServletContext context = request.getSession().getServletContext();
        context.setAttribute("verificationCode", verificationCode);
        System.out.println(verificationCode);
        String yzmInfo="您正在本站进行验证操作，如非您本人操作，请忽略此信息。验证码1分钟内有效，如果超时请重新获取您的验证码为："+verificationCode;
        NameValuePair[] data ={ new NameValuePair("Uid", "久悠哥哥"),new NameValuePair("Key", "d41d8cd98f00b204e980"),new NameValuePair("smsMob",mobile),new NameValuePair("smsText",yzmInfo)};
        post.setRequestBody(data);
        client.executeMethod(post);
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:"+statusCode);
        for(Header h : headers)
        {
            System.out.println(h.toString());
        }
        String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        System.out.println(result); //打印返回消息状态      1成功
        response.setContentType("text/html;charset=utf-8");
        if (result.equals("1")){
        context.getAttribute("verificationCode");
        response.getWriter().println("发送成功");


        System.out.println("获取到session作用域中的验证码" + context.getAttribute("verificationCode"));

        }else{
            response.getWriter().println("发送失败");
        }


//        post.releaseConnection();

    }


    //免密登陆
    protected void secretFreeLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setContentType("text/html;charset=utf-8");
        System.out.println("-----------------免密登陆开始-----------------");
        ServletContext context = request.getSession().getServletContext();
        //获取系统生成的验证码
        String verificationCode1 = (String) context.getAttribute("verificationCode");
        //获取用户输入的验证码
        String verificationCode2 = request.getParameter("verificationCode2");
        System.out.println(verificationCode2);
        if (verificationCode1.equals(verificationCode2)) {
            System.out.println("验证码正确");
            //执行userDao查询该用户
            System.out.println(request.getParameter("mobile"));
            User loginUserInfo = userService.mobileLoginAndRegister(request.getParameter("mobile"));
            String jsonStr = JSON.toJSONString(loginUserInfo);
            System.out.println(jsonStr);
            Cookie cookie = new Cookie("loginUserInfo", URLEncoder.encode(jsonStr, "utf-8"));
            cookie.setMaxAge(60 * 60 * 10);
            cookie.setPath("/");
            response.addCookie(cookie);
            context.setAttribute("verificationCode", "1928918281");
            UserResponseData userResponseData = new UserResponseData();
            userResponseData.setCode(200);
            userResponseData.setMessage("验证码正确");
            userResponseData.setData(null);
            String responseJsonStr = JSON.toJSONString(userResponseData);
            response.getWriter().println(responseJsonStr);
            //更新验证码

        } else {
            UserResponseData userResponseData = new UserResponseData();
            userResponseData.setCode(400);
            userResponseData.setMessage("验证码错误");
            userResponseData.setData(null);
            String jsonStr = JSON.toJSONString(userResponseData);
            response.getWriter().println(jsonStr);//正确
        }
        //先执行数据库查询该账号属否存在，如果存在提示已存在，直接登陆，否则提示注册
    }

    //账号密码登陆
    protected void mobileAndPassLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        System.out.println("账号密码登陆");
        User user = userService.mobileAndPassLogin(request.getParameter("mobile"), request.getParameter("pass"));

        UserResponseData userResponseData = new UserResponseData();
        userResponseData.setCode(user==null?400:200);
        userResponseData.setMessage(user==null?"账号或密码错误":"信息正确");
        userResponseData.setData(user);

        String userResponseJsonStr=JSON.toJSONString(userResponseData);



        String userJsonStr = JSON.toJSONString(user);
        Cookie cookie = new Cookie("loginUserInfo", URLEncoder.encode(userJsonStr, "utf-8"));
        cookie.setMaxAge(60 * 60 * 10);
        cookie.setPath("/");
        response.addCookie(cookie);//存入cookie
        response.getWriter().println(userResponseJsonStr);//正确

    }


    //QQ登陆
    protected void qqLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setContentType("text/html;charset=utf-8");
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
        } catch (QQConnectException e) {
            e.printStackTrace();
        }

    }

    //QQ登陆回调
    protected void qqCallback(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("QQ登陆回调");
        response.setCharacterEncoding("UTF-8");
        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            String accessToken = null,
                    openID = null;
            long tokenExpireIn = 0L;
            if (accessTokenObj.getAccessToken().equals("")) {
                System.out.print("没有获取到响应参数");
            } else {
                accessToken = accessTokenObj.getAccessToken();
                tokenExpireIn = accessTokenObj.getExpireIn();
                OpenID openIDObj = new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                System.out.println(openID);
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                //生成时间
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
                String time = formatter.format(date);
                //生成uuid
                String uuid = null;
                for (int i = 0; i < 5; i++) {
                    //注意replaceAll前面的是正则表达式
                    uuid = UUID.randomUUID().toString().replaceAll("-", "");
                }
                //1:用户唯一ID  2:QQ用户的昵称   3:默认密码123456   4:QQ用户的性别     5:手机号为空      6:QQ用户的唯一ID       7:注册时间      8:QQ用户的头像       9:QQ用户的邮箱   10:用户的余额
                User user = new User(uuid, userInfoBean.getNickname(), "123456", userInfoBean.getGender(), null, openID, time, userInfoBean.getAvatar().getAvatarURL100(), openID + "@qq.com", 0);
                UserService userService = new UserServiceImpl();
                User resultUserInfo = userService.qqRegister(user);
                System.out.println(resultUserInfo);
                String jsonStr = JSON.toJSONString(resultUserInfo);
                Cookie cookie = new Cookie("loginUserInfo", URLEncoder.encode(jsonStr, "utf-8"));
                cookie.setMaxAge(60 * 60 * 10);
                cookie.setPath("/");
                response.addCookie(cookie);//存入cookie
                response.sendRedirect("http://127.0.0.1:5500/wmltWeb/index.html");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //找回密码 参数1 手机号 参数2 新的密码
    protected void resetPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    }
    //根据用户id获取用户信息
    protected void getUserInfoByUserId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("userId"));
        UserService userService = new UserServiceImpl();
        User user = userService.getUserInfoByUserId(request.getParameter("userId"));
        System.out.println(user);
        response.setContentType("text/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        String userData = jsonObject.toJSONString(user);
        System.out.println(userData);
        response.getWriter().println(userData);
    }
    /**
     * @description: 修改密码
     * @param:
     * @return:
     * @author liyuxiang
     * @date: 2021/4/8 4:31 下午
     */
    protected void changePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("userId"));
        UserService userService = new UserServiceImpl();
        int result= userService.changePassword(request.getParameter("userId"),request.getParameter("password"));
        System.out.println(result);
        response.setContentType("text/json;charset=utf-8");
        UserResponseData userResponseData=new UserResponseData();
        userResponseData.setCode(result>0?200:400);
        userResponseData.setMessage(result>0?"成功":"失败");
        JSONObject jsonObject = new JSONObject();
        String userData = jsonObject.toJSONString(userResponseData);
        System.out.println(userData);
        response.getWriter().println(userData);
    }


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        if ("/user/secretFreeLogin".equals(path)) {
            secretFreeLogin(req, resp);
        } else if ("/user/mobileAndPassLogin".equals(path)) {
            mobileAndPassLogin(req, resp);
        } else if ("/user/qqLogin".equals(path)) {
            qqLogin(req, resp);
        } else if ("/user/sendMessage".equals(path)) {
            sendMessage(req, resp);
        } else if ("/afterlogin".equals(path)) {
            qqCallback(req, resp);
        } else if ("/user/resetPassword".equals(path)) {

        } else if ("/user/adminLogin".equals(path)) {
            adminLogin(req, resp);
        } else if ("/user/getUserNumber".equals(path)) {
            getUserNumber(req, resp);
        } else if ("/user/getAllUserInfo".equals(path)) {
            getAllUserInfo(req, resp);
        } else if ("/user/deleteUserInfo".equals(path)) {
            deleteUserInfo(req, resp);
        } else if ("/user/getUserInfoByUserId".equals(path)) {
            getUserInfoByUserId(req, resp);
        }else if("/user/changePassword".equals(path)){
            changePassword(req, resp);
        }else if("/user/getUserIdInfoByUser".equals(path)){
            getUserIdInfoByUser(req, resp);
        }else  if ("/user/updateUserManager".equals(path)){
            updateUserManager(req,resp);
        }else if("/user/getUserCbByUserId".equals(path)){
            getUserCbByUserId(req, resp);
        }


    }

    protected void getUserIdInfoByUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("articleId"));
        UserService userService = new UserServiceImpl();
        List<Article> articleList= userService.getUserIdInfoByUser(request.getParameter("articleId"));

        response.setContentType("text/json;charset=utf-8");

        JSONObject jsonObject = new JSONObject();
        String userData = jsonObject.toJSONString(articleList);
        System.out.println(userData);
        response.getWriter().println(userData);
    }

    /**
     * @description: 用户修改信息
     * @param:
     * @return:
     */
    protected void updateUserManager(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        JSONObject jsonObject = GetRequestJsonUtils.getRequestJsonObject(response, request);
        System.out.println("正在操作。。。");
        System.out.println(jsonObject.getString("userid"));

        //获取当前登录用户
        String userid=jsonObject.getString("userid");

        //获取用户修改信息--用户名
        String username = jsonObject.getString("userName");
        //获取用户修改信息--手机号
        String mobile = jsonObject.getString("mobile");
        //获取用户修改信息--邮箱
        String email = jsonObject.getString("email");
        //获取用户修改信息--性别
        String sex = jsonObject.getString("sex");
        //获取用户修改信息--个人简介
        String profile = jsonObject.getString("profile");
        System.out.println(jsonObject.getString("userName"));
        System.out.println(jsonObject.getString("mobile"));
        System.out.println(jsonObject.getString("email"));
        System.out.println(jsonObject.getString("sex"));
        System.out.println(jsonObject.getString("profile"));
        User user=new User(username,sex,mobile,email,profile);
        UserService userService = new UserServiceImpl();
        int result=userService.updateUserManager(userid,user);
        response.getWriter().println(result);
    }

    /**
     * @description: 获取用户cb
     * @param:
     * @return:
     * @author liyuxiang
     * @date: 2021/4/15 12:53 下午
     */
    protected void getUserCbByUserId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/text;charset=utf-8");
        UserService userService = new UserServiceImpl();
        int cb = userService.getUserCbByUserId(request.getParameter("userId"));
        response.getWriter().println(cb);
    }
}
